package com.example.club.clubmanage.ui;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.example.club.clubmanage.R;
import com.example.club.clubmanage.databinding.ActivityMainBinding;
import com.example.club.clubmanage.service.MQTTService;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private String TAG = "MainActivity";
    private ActivityMainBinding mBinding;
    private boolean isDoubleClick =  false;
    private Timer timer = new Timer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);




        mBinding.bottomBar.setContainer(R.id.fl_container)
                .setTitleBeforeAndAfterColor("#bfbfbf", "#ff6c00")
                .addItem(FirstFragment.class,
                        "订单",
                        R.mipmap.main_tab_bar_order_unselect,
                        R.mipmap.main_tab_bar_order_select)
                .addItem(SecondFragment.class,
                        "我的",
                        R.mipmap.main_tab_bar_mine_unselect,
                        R.mipmap.main_tab_bar_mine_select)
                .build();
        // 检查权限
        requestPermission();

        mBinding.alarm.setOnClickListener(v -> {
            Log.d(TAG,"点击发送消息");
            MQTTService.publish("发生火警！");
        });
    }
    private void requestPermission(){
//        Manifest.permission.CAMERA, ,Manifest.permission.READ_EXTERNAL_STORAGE
        // Manifest.permission.ACCESS_FINE_LOCATION
        String[] perms = { Manifest.permission.READ_PHONE_STATE};
        if (EasyPermissions.hasPermissions(this, perms)) {

            // 已经申请过权限，做想做的事
            // 启动MQTT推送服务
            Log.d(TAG,"启动MQTT推送服务");
            startService(new Intent(this, MQTTService.class));
        } else {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(this, "请求权限",
                    1, perms);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                handleCilick();// 实现再按一次退出
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private void handleCilick() {
        if (!isDoubleClick) {
            isDoubleClick = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isDoubleClick = false;
                }
            }, 2000);
        } else {
            this.finish();
            android.os.Process.killProcess(android.os.Process.myPid());
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG,"onPermissionsGranted:"+requestCode);
        startService(new Intent(this, MQTTService.class));

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG,"onPermissionsDenied:"+requestCode);

        //处理权限名字字符串
        StringBuffer sb = new StringBuffer();
        for (String str : perms){
            sb.append(str);
            sb.append("\n");
        }
        sb.replace(sb.length() - 2,sb.length(),"");
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            Toast.makeText(this, "已拒绝权限" + sb + "并不再询问" , Toast.LENGTH_SHORT).show();
            new AppSettingsDialog
                    .Builder(this)
                    .setRationale("此功能需要" + sb + "权限，否则无法使用报警通知功能，是否打开设置")
                    .setPositiveButton("是")
                    .setNegativeButton("否")
                    .build()
                    .show();
        }
    }
}
